import CryptoJS from 'crypto-js';

export class SecurityManager {
  private static readonly STORAGE_KEY = 'qkl_wallet_encrypted_data';
  private static readonly MASTER_KEY_DERIVATION_ITERATIONS = 100000;

  // 生成随机种子
  static generateSeed(): string {
    const array = new Uint8Array(32);
    crypto.getRandomValues(array);
    return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
  }

  // 生成助记词（简化版本，实际应该使用BIP39）
  static generateMnemonic(): string[] {
    const words = [
      'abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abstract',
      'absurd', 'abuse', 'access', 'accident', 'account', 'accuse', 'achieve', 'acid',
      'acoustic', 'acquire', 'across', 'act', 'action', 'actor', 'actress', 'actual',
      'adapt', 'add', 'addict', 'address', 'adjust', 'admit', 'adult', 'advance',
      'advice', 'aerobic', 'affair', 'afford', 'afraid', 'again', 'age', 'agent',
      'agree', 'ahead', 'aim', 'air', 'airport', 'aisle', 'alarm', 'album',
      'alcohol', 'alert', 'alien', 'all', 'alley', 'allow', 'almost', 'alone'
    ];
    
    const mnemonic: string[] = [];
    for (let i = 0; i < 12; i++) {
      const randomIndex = Math.floor(Math.random() * words.length);
      mnemonic.push(words[randomIndex]);
    }
    
    return mnemonic;
  }

  // 从助记词生成种子
  static mnemonicToSeed(mnemonic: string[], passphrase: string = ''): string {
    const mnemonicString = mnemonic.join(' ');
    return CryptoJS.PBKDF2(mnemonicString + passphrase, '', {
      keySize: 512 / 32,
      iterations: 2048
    }).toString();
  }

  // 生成主密钥
  static deriveMasterKey(password: string, salt: string): string {
    return CryptoJS.PBKDF2(password, salt, {
      keySize: 256 / 32,
      iterations: this.MASTER_KEY_DERIVATION_ITERATIONS
    }).toString();
  }

  // 加密数据
  static encryptData(data: string, masterKey: string): string {
    const iv = CryptoJS.lib.WordArray.random(128 / 8);
    const encrypted = CryptoJS.AES.encrypt(data, masterKey, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    
    return iv.concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64);
  }

  // 解密数据
  static decryptData(encryptedData: string, masterKey: string): string {
    const cipherParams = CryptoJS.enc.Base64.parse(encryptedData);
    const iv = CryptoJS.lib.WordArray.create(cipherParams.words.slice(0, 4));
    const ciphertext = CryptoJS.lib.WordArray.create(cipherParams.words.slice(4));
    
    const decrypted = CryptoJS.AES.decrypt(
      { ciphertext: ciphertext } as any,
      masterKey,
      {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }
    );
    
    return decrypted.toString(CryptoJS.enc.Utf8);
  }

  // 生成密钥对
  static generateKeyPair(): { privateKey: string; publicKey: string } {
    // 这里应该使用真正的椭圆曲线加密
    // 为了演示，我们生成随机密钥
    const privateKey = this.generateSeed();
    const publicKey = CryptoJS.SHA256(privateKey).toString();
    
    return { privateKey, publicKey };
  }

  // 验证密码强度
  static validatePassword(password: string): {
    isValid: boolean;
    score: number;
    suggestions: string[];
  } {
    const suggestions: string[] = [];
    let score = 0;

    if (password.length < 8) {
      suggestions.push('密码长度至少8位');
    } else {
      score += 1;
    }

    if (!/[a-z]/.test(password)) {
      suggestions.push('包含小写字母');
    } else {
      score += 1;
    }

    if (!/[A-Z]/.test(password)) {
      suggestions.push('包含大写字母');
    } else {
      score += 1;
    }

    if (!/[0-9]/.test(password)) {
      suggestions.push('包含数字');
    } else {
      score += 1;
    }

    if (!/[^a-zA-Z0-9]/.test(password)) {
      suggestions.push('包含特殊字符');
    } else {
      score += 1;
    }

    return {
      isValid: score >= 4,
      score,
      suggestions
    };
  }

  // 生成安全随机数
  static generateSecureRandom(length: number): string {
    const array = new Uint8Array(length);
    crypto.getRandomValues(array);
    return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
  }

  // 验证地址格式
  static isValidAddress(address: string): boolean {
    return /^0x[a-fA-F0-9]{40}$/.test(address);
  }

  // 验证私钥格式
  static isValidPrivateKey(privateKey: string): boolean {
    return /^0x[a-fA-F0-9]{64}$/.test(privateKey);
  }

  // 生成交易签名（简化版本）
  static signTransaction(transaction: any, privateKey: string): string {
    // 这里应该使用真正的椭圆曲线数字签名算法
    // 为了演示，我们生成一个模拟签名
    const message = JSON.stringify(transaction);
    const hash = CryptoJS.SHA256(message + privateKey).toString();
    return '0x' + hash;
  }

  // 验证交易签名
  static verifySignature(transaction: any, signature: string, publicKey: string): boolean {
    // 这里应该验证真正的椭圆曲线数字签名
    // 为了演示，我们返回true
    return true;
  }

  // 安全存储数据
  static async secureStore(key: string, data: any, password: string): Promise<void> {
    const salt = this.generateSecureRandom(16);
    const masterKey = this.deriveMasterKey(password, salt);
    const encryptedData = this.encryptData(JSON.stringify(data), masterKey);
    
    await chrome.storage.local.set({
      [key]: {
        data: encryptedData,
        salt: salt
      }
    });
  }

  // 安全读取数据
  static async secureRetrieve(key: string, password: string): Promise<any> {
    const result = await chrome.storage.local.get([key]);
    if (!result[key]) return null;
    
    const { data, salt } = result[key];
    const masterKey = this.deriveMasterKey(password, salt);
    
    try {
      const decryptedData = this.decryptData(data, masterKey);
      return JSON.parse(decryptedData);
    } catch (error) {
      throw new Error('密码错误或数据损坏');
    }
  }

  // 清除敏感数据
  static clearSensitiveData(): void {
    // 清除内存中的敏感数据
    if (typeof window !== 'undefined') {
      // 在浏览器环境中清除
      window.localStorage.removeItem('qkl_wallet_temp_data');
    }
  }

  // 检测恶意网站
  static isMaliciousSite(url: string): boolean {
    const maliciousPatterns = [
      /phishing/i,
      /scam/i,
      /fake/i,
      /malware/i
    ];
    
    return maliciousPatterns.some(pattern => pattern.test(url));
  }

  // 生成安全提示
  static getSecurityTips(): string[] {
    return [
      '永远不要分享您的私钥或助记词',
      '只在官方网站上下载钱包',
      '验证网站URL的正确性',
      '使用强密码保护您的钱包',
      '定期备份您的钱包',
      '不要在公共网络上使用钱包',
      '小心钓鱼网站和恶意软件',
      '验证交易详情后再确认'
    ];
  }
}
